import { resourceComDispatch } from "@/prototype/global/local/constant"
import { colorful, isInArray } from "@/utils"

export default class BaseMissonExtension extends Room {
    // 搬运基本任务
    public Task_Carry(misson:MissionModel):void{
        /* 搬运任务需求 sourcePosX,Y sourceRoom targetPosX,Y targetRoom num  rType  */
        // 没有任务数据 或者数据不全就取消任务
        if (!misson.data) this.DeleteMisson(misson.id)
        if (!misson.CreepBind) this.DeleteMisson(misson.id)
        /* 生产相关爬虫 */
        for (var cRole in misson.CreepBind)
        {
            /* manage 和 transport是例外，他们是常驻 */
            if (cRole == 'manage' || cRole == 'transport')
            continue
            if (!global.CreepNumData[this.name][cRole].must)
            {
                global.CreepNumData[this.name][cRole].num += misson.CreepBind[cRole].num
            }
        }
    }

    /* 判断lab的boost搬运模块 */
    public Check_Lab(misson:MissionModel,role:string,tankType:'storage' | 'terminal' | 'complex'):boolean
    {
        var id:string
        if (tankType == 'storage')
        {
            if (!this.memory.StructureIdData.storageID )return false
            id = this.memory.StructureIdData.storageID
        }
        else if (tankType == 'terminal')
        {
            if (!this.memory.StructureIdData.terminalID )return false
            id = this.memory.StructureIdData.terminalID
        }
        var tank_ = Game.getObjectById(id) as Tank
        if (!tank_ && id) return false
        /* 先负责lab的填充 */
        for (var i in misson.LabBind)
        {
            var All_i_Num:number
            if (tankType == 'complex')
            {
                var terminal = Game.getObjectById(this.memory.StructureIdData.terminalID) as StructureTerminal
                var storage = Game.getObjectById(this.memory.StructureIdData.storageID) as StructureStorage
                if (!terminal || !storage)
                {
                    if (!terminal && storage) tank_ = storage
                    else if (terminal && !storage) tank_ = terminal
                    else return false
                }
                else
                {
                    var terminalNum = terminal.store.getUsedCapacity(misson.LabBind[i] as ResourceConstant)
                    var storageNum = storage.store.getUsedCapacity(misson.LabBind[i] as ResourceConstant)
                    tank_ = terminalNum>storageNum?terminal:storage
                }
            }
            if (!tank_) return false
            All_i_Num = tank_.store.getUsedCapacity(misson.LabBind[i] as ResourceConstant)
            if (All_i_Num < 4000)
            {
                var terminal = Game.getObjectById(this.memory.StructureIdData.terminalID) as StructureTerminal
                /* 小于4500时先尝试资源调度，如果调度失败就购买  cr太少就不购买 */
                if (terminal && !this.Resource_Dispatch(misson.LabBind[i] as ResourceConstant,2500))
                if (terminal && this.MarketMissonNum(misson.LabBind[i] as ResourceConstant,'资源购买') == 0 && Game.market.credits > 10000000 && terminal.store.getUsedCapacity(misson.LabBind[i] as ResourceConstant) < 2500)
                {
                    var marketTask = this.Public_Buy(misson.LabBind[i] as ResourceConstant,2000,65,120)
                    this.AddMisson(marketTask)
                }
            }
            var disLab = Game.getObjectById(i)  as StructureLab
            if (!disLab) return false
            if (disLab.store.getUsedCapacity(misson.LabBind[i] as ResourceConstant) < 800)
            {
                if (All_i_Num < 2000)
                return false
                var roleData:BindData = {}
                roleData[role] = {num:1,bind:[]}
                var carryTask = this.Public_Carry(roleData,25,this.name,tank_.pos.x,tank_.pos.y,this.name,disLab.pos.x,disLab.pos.y,misson.LabBind[i] as ResourceConstant,2000)
                this.AddMisson(carryTask)
                return false
            }
        }
        return true 
    }
    

    /* 资源deal购买模块 */
    public Deal_Resource(rType:ResourceConstant,num:number,range:number,max:number):void{
        /* 遍历terminal是否已经有了相关deal任务 */
        for (var misson of this.memory.Misson['Structure'])
        {
            if (misson.name == '资源购买' && misson.data.rType == rType) return 
        }
        /* 没有就开始下购买任务 */
        var marketTask = this.Public_Buy(rType,num,range,max)
        this.AddMisson(marketTask)
    }

    /* 全局资源调度模块 true代表成功、调度正在途中  false代表没有可用调度 */
    public Resource_Dispatch(rType:ResourceConstant,num:number):boolean{
        Loop1:
        for (var name in Memory.ControlPlan)
        {
            if (name == this.name) continue
            // 只有七级以上的房间才有资格参与资源调度
            if (!Game.rooms[name].memory.StructureIdData || Game.rooms[name].controller.level < 7) continue
            if (!global.Stru[name]) continue
            let storage_ = global.Stru[name]['storage'] as StructureStorage
            if (!storage_) continue
            // 有传送任务就pass掉
            if (!Game.rooms[name].memory.Misson) continue Loop1
            for (var miss of Game.rooms[name].memory.Misson['Structure'])
            {
                // 如果房间有合成任务 仓库数量 - 实验室目标数量 < 调度需求数量 pass
                if (miss.name == '资源合成' && isInArray([miss.data.raw1,miss.data.raw2],rType))
                {
                    if (storage_.store.getUsedCapacity(rType) - miss.data.num < num) continue Loop1
                }
                /* 说明资源调度已经正在途中了 */
                if (miss.name == '资源传送' && miss.data.disRoom == this.name)
                {
                    return true
                }
                if ((miss.name == '资源传送' && miss.data.disRoom != this.name)) continue Loop1
                // 如果房间有boost任务
            }
            /* 如果该房间有合成调度任务 */
            if (Game.rooms[name].memory.ComDispatchData.length >0)
            {
                /* 该房间合成调度的最终目标材料 disCom */
                var disCom = Game.rooms[name].memory.ComDispatchData[Game.rooms[name].memory.ComDispatchData.length - 1].res
                if (isInArray(resourceComDispatch[disCom],rType) && rType != disCom && storage_.store.getUsedCapacity(rType) - (Game.rooms[name].memory.ComDispatchData[0].dispatch_num+3000) < num)
                continue Loop1
            }
            if (storage_.store.getUsedCapacity(rType) >= num)    // 只有资源足够的情况下才会传送
            {
                /* 下资源传送任务 */
                Game.rooms[name].AddMisson(Game.rooms[name].Public_Send(this.name,rType,num))
                return true
            }
        }
        return false
    }

    /* 获取已有订单中的订单ID 并且自动创建好Order */
    // public GetOrder(rType:ResourceConstant,price:number,num:number,marketType:'buy'|'sell'):string{
    //     if(!this.memory.marketID) this.memory.marketID = {}
    //     if(this.memory.marketID[rType])
    //     {
    //         /* 如果已经存储ID信息了，就用已经存储的，如果过期了就继续寻找 */
    //         var Order = Game.market.getOrderById(this.memory.marketID[rType] as string)
    //         if(Order)
    //         {
    //             Game.market.changeOrderPrice(i,price)
    //             if(Order.remainingAmount >= num)
    //             {
    //                 this.memory.marketID[rType] = Order.id
    //                 return Order.id
    //             }
    //             else
    //             {
    //                 Game.market.extendOrder(i,num - Order.remainingAmount)
    //                 this.memory.marketID[rType] = Order.id
    //                 return Order.id
    //             }
    //         }
    //         else
    //         {
    //             delete this.memory.marketID[rType]
    //         }
    //     }
    //     /* 继续寻找 */
    //     for (var i in Game.market.orders)
    //     {
    //         var Order = Game.market.orders[i]
    //         if(Order.roomName == this.name && Order.resourceType == rType && Order.type == marketType)
    //         {
    //             Game.market.changeOrderPrice(i,price)
    //             if(Order.remainingAmount >= num)
    //             {
    //                 this.memory.marketID[rType] = Order.id
    //                 return Order.id
    //             }
    //             else
    //             {
    //                 Game.market.extendOrder(i,num - Order.remainingAmount)
    //                 this.memory.marketID[rType] = Order.id
    //                 return Order.id
    //             }
    //         }    
    //     }
    //     /* 还没有就创建订单 */
    //     return
    // }
    /* 创建订单 如果有ID信息就直接拓展ID的订单，如果没有就寻找，如果还没有就新建 */
    public MakeOrder(marketType:'buy'|'sell',rType:ResourceConstant,num:number,price:number):boolean{
        if(!this.memory.marketID) this.memory.marketID = {}
        if(!this.memory.marketID['buy']) this.memory.marketID['buy'] = {}
        if(!this.memory.marketID['sell']) this.memory.marketID['sell'] = {}
        if(this.memory.marketID[marketType][rType])
        {
            var Order = Game.market.getOrderById(this.memory.marketID[marketType][rType])
            if(Order)
            {
                if(price > 0.05)
                {
                    /* 买单如果价格高了就不换改价格 */
                    if(marketType == 'buy' && Order.price > price) {}
                    else
                    Game.market.changeOrderPrice(Order.id,price)
                }
                if(Order.remainingAmount >= num)
                {
                    this.memory.marketID[marketType][rType] = Order.id
                    console.log(colorful(`房间${this.name}MarketID中OrderID存在！资源为:${rType},交易类型为${marketType},价格为${price},数量为${Order.remainingAmount}`,'green',true))
                    return true
                }
                else
                {
                    Game.market.extendOrder(Order.id,num - Order.remainingAmount)
                    console.log(colorful(`房间${this.name}MarketID中OrderID存在！资源为:${rType},交易类型为${marketType},价格为${price},数量为${Order.remainingAmount}`,'green',true))
                    this.memory.marketID[marketType][rType] = Order.id
                    return true
                }
            }
            else
            {
                delete this.memory.marketID[marketType][rType]
            }
        }
        /* 如果没有相应的ID记录，需要从已存在而且已经Inactive的订单里找 */
        for (var i in Game.market.orders)
        {
            var Order = Game.market.orders[i]
            if(Order.roomName == this.name && Order.resourceType == rType && Order.type == marketType)
            {
                Game.market.changeOrderPrice(i,price)
                if(Order.remainingAmount >= num)
                {
                    console.log(colorful(`房间${this.name}Order已经存在！资源为:${rType},交易类型为${marketType},价格为${price},数量为${Order.remainingAmount}`,'green',true))
                    this.memory.marketID[marketType][rType] = Order.id
                    return true
                }
                else
                {
                    console.log(colorful(`房间${this.name}Order拓展成功！资源为:${rType},交易类型为${marketType},价格为${price},拓展了${num - Order.remainingAmount}`,'green',true))
                    Game.market.extendOrder(i,num - Order.remainingAmount)
                    this.memory.marketID[marketType][rType] = Order.id
                    return true
                }
            }   
        }
        /* 还没有就创建Order */
        var result = Game.market.createOrder({
            type: marketType,
            resourceType: rType,
            price: price,
            totalAmount: num,
            roomName: this.name   
        })
        if(result == 0)
        {
            console.log(colorful(`房间${this.name}Order挂载成功！资源为:${rType},交易类型为${marketType},价格为${price},数量为${num},返回码为${result}`,'green',true))
            return true
            
        }
        else
        {
            console.log(colorful(`房间${this.name}不明原因Order挂载失败！资源为:${rType},交易类型为${marketType},价格为${price},数量为${num},错误码为${result}`,'red',true))
            return false
        }

    }
}